package dongbai.soft.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import dongbai.soft.entity.GoodOrderEntity;
import dongbai.soft.entity.ReceiptEntity;
import dongbai.soft.feignclient.DispatchClient;
import dongbai.soft.service.GoodOrderService;
import dongbai.soft.service.ReceiptService;
import dongbai.soft.utils.Constant;
import dongbai.soft.utils.PageUtils;
import dongbai.soft.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author SingDeer
 * @email
 * @date 2023-06-29 15:51:52
 */
@RestController
@RequestMapping("")
@SuppressWarnings("unchecked")
public class FinanceController {
    int month = 29, year = 364;
    @Autowired
    private GoodOrderService goodOrderService;
    @Autowired
    private ReceiptService receiptService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisTemplate<String, String> Strredis;
    @Autowired
    private DispatchClient dispatchClient;

    /**
     * 回执列表-
     */
    @RequestMapping("/receipt")
    public R receipt(@RequestBody Map<String, Object> params) {
        PageUtils page = receiptService.queryPage(params);
        return R.ok().put("page", page);

    }

    /**
     * 货单列表-
     */
    @RequestMapping("/goodorder")
    public R goodorder(@RequestBody Map<String, Object> params) {
        PageUtils page = goodOrderService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 创建货单-
     */
    @RequestMapping("/newgoodorder")
    //@RequiresPermissions("finance:goodorder:save")
    public R newgoodorder(@RequestBody Map<String, Object> maps) {
        GoodOrderEntity goodOrderEntity = new GoodOrderEntity(maps);
        goodOrderService.save(goodOrderEntity);
        int num = Integer.valueOf(Strredis.opsForList().index(Constant.PRO_NUM, 7));
        BigDecimal price = new BigDecimal(String.valueOf(redisTemplate.opsForList().index(Constant.PRO_PRICE, 7)));
        num += goodOrderEntity.getPnum();
        price = price.add(goodOrderEntity.getPrice());
        Strredis.opsForList().set(Constant.PRO_NUM, 7, num + "");
        Strredis.opsForList().set(Constant.PRO_PRICE, 7, price + "");
        return R.ok();
    }


    /**
     * 回执结算，分站调用
     */
    @RequestMapping("/rclose")
    //@RequiresPermissions("finance:goodorder:update")
    public R rclose(@RequestBody Map<String, Object> maps) {
        List<Map<String, Object>> datas = (List<Map<String, Object>>) maps.get("list");
        List<ReceiptEntity> receiptEntities = new ArrayList<>();
        BigDecimal total = new BigDecimal(0);
        List<String> oids = new ArrayList<>();
        for (Map<String, Object> data : datas) {
            oids.add((String) data.get("OID"));
            ReceiptEntity receiptEntity = new ReceiptEntity(data);
            total = total.add(receiptEntity.getDeliverPrice());
            total = total.add(receiptEntity.getPrice());
            receiptEntities.add(receiptEntity);
        }
        //1.更新订单状态为已结算
        Map<String, Object> smap = new HashMap<>();
        smap.put("isend", 2);
        smap.put("OIDS", oids);
        dispatchClient.setStatus(smap);

        //2.更新当日总利润
        BigDecimal money = (BigDecimal) redisTemplate.opsForList().rightPop(Constant.PROFIT);
        assert money != null;
        money = money.add(total);
        redisTemplate.opsForList().rightPush(Constant.PROFIT, money);

        //3.更新该分站的当日利润和单数信息
        String TRID = (String) datas.get(0).get("TRID");

        //更新利润信息
        BigDecimal line = (BigDecimal) redisTemplate.opsForList().rightPop(Constant.TR_LINE + TRID);
        assert line != null;
        line = line.add(total);
        redisTemplate.opsForList().rightPush(Constant.TR_LINE + TRID, line);

        //更新单数信息
        int sum = (int) redisTemplate.opsForList().rightPop(Constant.TR_BAR + TRID);
        sum = sum + datas.size();
        redisTemplate.opsForList().rightPush(Constant.TR_BAR + TRID, sum);
        receiptService.saveBatch(receiptEntities);
        return R.ok();
    }

    /**
     * 货单结算-
     * total是此次批量结算的利润
     * t1t2t3为不同种类货单数量
     */
    @RequestMapping("/gclose")
    //@RequiresPermissions("finance:goodorder:update")
    public R gclose(@RequestBody Map<String, String> maps) {
        List<String> gids = new ArrayList<>(Arrays.asList(maps.get("GID").split(",")));
        List<GoodOrderEntity> goodOrderEntities = goodOrderService.list(new QueryWrapper<GoodOrderEntity>().in("GID", gids));
        BigDecimal total = new BigDecimal(0);
        int t1 = 0, t2 = 0, t3 = 0;
        for (GoodOrderEntity goodOrderEntity : goodOrderEntities) {
            goodOrderEntity.setIspaid(true);
            goodOrderEntity.setDealTime(new Date());
            if (goodOrderEntity.getType().equals(0)) {
                total = total.subtract(goodOrderEntity.getPrice());
                t1 += 1;
            } else if (goodOrderEntity.getType().equals(1)) {
                total = total.add(goodOrderEntity.getPrice());
                t2 += 1;
            } else {
                t3 += 1;
            }

        }


        //1.更新当日总利润
        BigDecimal profit = (BigDecimal) redisTemplate.opsForList().rightPop(Constant.PROFIT);
        assert profit != null;
        profit = profit.add(total);
        redisTemplate.opsForList().rightPush(Constant.PROFIT, profit);
        goodOrderService.updateBatchById(goodOrderEntities);

        //2.更新当日货单分类
        String info = (String) redisTemplate.opsForList().rightPop(Constant.CAL_PIE);
        assert info != null;
        List<Integer> num = Arrays.stream(info.split(", "))
                .map(Integer::parseInt).collect(Collectors.toList());
        num.set(0, num.get(0) + t1);
        num.set(1, num.get(1) + t2);
        num.set(2, num.get(2) + t3);
        redisTemplate.opsForList().rightPush(Constant.CAL_PIE, num.toString().substring(1, num.toString().length() - 1));
        return R.ok();
    }

    /**
     * 数据可视化-热力图
     */
    @RequestMapping("/heatmap")
    //@RequiresPermissions("finance:goodorder:update")
    public R heatmap() {
        return R.ok().put("list", receiptService.heatlist(year));
    }

    /**
     * 数据可视化-日历饼图
     */
    @RequestMapping("/calpie")
    //@RequiresPermissions("finance:goodorder:update")
    public R calpie() {
        List<String> calinfos = redisTemplate.opsForList().range(Constant.CAL_PIE, 0, -1);
        assert calinfos != null;
        List<List<Map<String, Object>>> pielist = new ArrayList<>();
        for (String info : calinfos) {
            List<Integer> num = Arrays.stream(info.split(", "))
                    .map(Integer::parseInt).collect(Collectors.toList());
            List<Map<String, Object>> data = new ArrayList<>();
            String[] names = {"进货单", "退货单", "亏损单"};
            for (int i = 0; i < 3; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", names[i]);
                map.put("value", num.get(i));
                data.add(map);
            }
            pielist.add(data);
        }
        return Objects.requireNonNull(R.ok().put("list", receiptService.heatlist(month))).put("pielist", pielist);
    }

    /**
     * 数据可视化-分站柱状折线图
     */
    @RequestMapping("/barline")
    //@RequiresPermissions("finance:goodorder:update")
    public R barline(@RequestBody Map<String, String> map) {
        //从redis获取七天折线图和柱状图数据
        List<BigDecimal> lineinfo = redisTemplate.opsForList().range(Constant.TR_LINE + map.get("TRID"), 0, -1);
        List<Integer> barinfo = redisTemplate.opsForList().range(Constant.TR_BAR + map.get("TRID"), 0, -1);

        //装配返回数据
        List<Map<String, Object>> datas = new ArrayList<>();

        Map<String, Object> linedata = new HashMap<>();
        linedata.put("type", "line");
        linedata.put("name", "交易总额");
        linedata.put("data", lineinfo);

        Map<String, Object> bardata = new HashMap<>();
        bardata.put("type", "bar");
        bardata.put("name", "交易单数");
        bardata.put("data", barinfo);

        datas.add(linedata);
        datas.add(bardata);
        return R.ok().put("list", datas);
    }


}
